/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * BuildingPanel.java
 *
 * Created on 11 Feb 2011, 11:21:01 AM
 */
package za.co.pas.spaceandtime.view.panel;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.util.List;
import java.util.ListIterator;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import za.co.pas.business.abstracts.AbstractView;
import za.co.pas.business.data.Company;
import za.co.pas.business.message.MessageObj;
import za.co.pas.spaceandtime.constant.STConstant;
import za.co.pas.spaceandtime.controller.BuildingDetailController;
import za.co.pas.spaceandtime.data.Building;
import za.co.pas.spaceandtime.message.MsgConstant;
import za.co.pas.spaceandtime.model.ext.BuildingDetailModel;
import za.co.pas.spaceandtime.model.list.BuildingListModel;
import za.co.pas.spaceandtime.mvc.SpaceAndTimeMVC;

/**
 *
 * @author alabuschagne
 */
public class BuildingListPanel extends JPanel implements AbstractView
{

    private List<Building> newBuildings;
    private boolean dirty = false;
    private BuildingListModel buildingListModel = new BuildingListModel();
    private BuildingDetailController buildingDetailController;// = (BuildingDetailController) MainFrame.stMVC.getController(SpaceAndTimeMVC.BUILDING_DETAIL_CONTROLLER);
    private BuildingDetailModel buildingDetailModel;

    /** Creates new form BuildingPanel */
    public BuildingListPanel()
    {
        initComponents();
        buildingDetailController = (BuildingDetailController) STConstant.stMVC.getController(SpaceAndTimeMVC.BUILDING_DETAIL_CONTROLLER);
        buildingDetailModel = (BuildingDetailModel) STConstant.stMVC.getModel(SpaceAndTimeMVC.BUILDING_DETAIL_MODEL);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        buildingList = new javax.swing.JList();

        setLayout(new java.awt.BorderLayout());

        buildingList.setModel(buildingListModel);
        buildingList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                buildingListMouseReleased(evt);
            }
        });
        jScrollPane1.setViewportView(buildingList);

        add(jScrollPane1, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    private void buildingListMouseReleased(java.awt.event.MouseEvent evt)//GEN-FIRST:event_buildingListMouseReleased
    {//GEN-HEADEREND:event_buildingListMouseReleased
        if (evt.isPopupTrigger())
        {
            JPopupMenu Pmenu = new JPopupMenu();

            JMenuItem menuItem = new JMenuItem("New");
            Pmenu.add(menuItem);
            menuItem.addActionListener(new ActionListener()
            {

                @Override
                public void actionPerformed(ActionEvent e)
                {
                    editBuilding(null);
                }
            });
            int k = buildingList.getSelectedIndex();
            if (k != -1)
            {
                menuItem = new JMenuItem("Edit");
                Pmenu.add(menuItem);
                menuItem.addActionListener(new ActionListener()
                {

                    @Override
                    public void actionPerformed(ActionEvent e)
                    {
                        int k = buildingList.getSelectedIndex();
                        if (k != -1)
                        {
                            Building b = (Building) buildingListModel.getElementAt(k);
                            editBuilding(b);
                        }
                    }
                });
            }
            Pmenu.show(evt.getComponent(), evt.getX(), evt.getY());
        }
    }//GEN-LAST:event_buildingListMouseReleased
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JList buildingList;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables

    private void editBuilding(Building b)
    {
        if (b == null)
        {
            buildingDetailController.requestMakeNewBuilding();
        }
        else
        {
            buildingDetailController.requestEditBuilding(b);
        }
    }

    private void updateData()
    {
        if (newBuildings == null)
        {
            return;
        }
    }

    public int checkBuildings(List<Building> sendNewBuildings)
    {
        //first set the text field data to newCompany fields
        updateData();
        if ((newBuildings == null) && (!isDirty()))
        {
            return JOptionPane.NO_OPTION;
        }
        else if ((newBuildings == null) && (isDirty()))
        {
            int resp = JOptionPane.showConfirmDialog(this, "Save changes?", "Unsaved data", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (resp == JOptionPane.YES_OPTION)
            {
                buildingDetailController.SaveBuildings(newBuildings);
            }
            return resp;
        }
        else if (newBuildings != null)
        {
            boolean ask = sendNewBuildings.size() != newBuildings.size();
            if (!ask)//size is the same, thus check each element
            {
                ask = false;
                ListIterator<Building> it = newBuildings.listIterator();
                while (it.hasNext())
                {
                    Building b = it.next();
                    ListIterator<Building> itNew = sendNewBuildings.listIterator();
                    while (itNew.hasNext())
                    {
                        Building b2 = itNew.next();
                        ask = !b.check(b2);
                        if (ask)
                        {
                            break;//out of inner loop
                        }
                    }
                    if (ask)
                    {
                        break;//out of outer loop
                    }
                }
            }
            if (ask)
            {
                int resp = JOptionPane.showConfirmDialog(this, "Save changes?", "Unsaved data", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
                if (resp == JOptionPane.YES_OPTION)
                {
                    buildingDetailController.SaveBuildings(newBuildings);
                }
                else
                {
                    return resp;
                }
            }
        }
        return JOptionPane.NO_OPTION;
    }

    @Override
    public void modelPropertyChange(PropertyChangeEvent evt)
    {
        /*if (evt.getPropertyName().compareTo(MsgConstant.BUILDING_LIST_CHANGED) == 0)
        {
            if (evt.getNewValue() instanceof List)
            {
                buildingListModel.setBuildings((List<Building>) evt.getNewValue());
                buildingList.updateUI();
                currentCompany = tempCompany;
            }
        }
        else*/ if (evt.getPropertyName().compareTo(MsgConstant.REQUEST_BUILDING_LIST_CHANGED) == 0)
        {
            if ((evt.getNewValue() != null) && (evt.getNewValue() instanceof List))
            {
                List<Building> sendNewBuildings = (List<Building>) evt.getNewValue();
                if (checkBuildings(sendNewBuildings) == JOptionPane.NO_OPTION)
                {
                    try
                    {
                        this.newBuildings = sendNewBuildings;
                        buildingDetailController.setBuildingList(sendNewBuildings);
                        buildingListModel.setBuildings((List<Building>) evt.getNewValue());
                        buildingList.updateUI();
                    }
                    catch (Exception ex)
                    {
                        ex.printStackTrace();
                    }
                }
            }
        }
        else if (evt.getPropertyName().compareTo(MessageObj.COMPANY_DETAILS_CHANGED) == 0)
        {
            if (evt.getNewValue() instanceof Company)
            {
                buildingDetailController.requestBuildingList((Company)evt.getNewValue(), true);
            }
        }
    }

    /**
     * @return the dirty
     */
    @Override
    public boolean isDirty()
    {
        return dirty;
    }

    /**
     * @param dirty the dirty to set
     */
    public void setDirty(boolean dirty)
    {
        this.dirty = dirty;
    }

        @Override
    public String getExtraTitle()
    {
        return null;
    }
}
